<?php

namespace app\common\model;

class GrowthLog extends Base
{
    // 设置当前模型对应的完整数据表名称
    protected $table = 'ddt_growth_log';
    // 主键ID
    protected $pk = 'log_id';

	//订单状态
	public static $typelist = [
		'1'=>'购买商品',
		'2'=>'购买服务',
		'3'=>'签到',
		'4'=>'分润',
	];

	public function getTypeCase($type){
		switch ($type){
			case 1:
				$cate = '+';
				break;
			case 2:
				$cate = '+';
				break;
			case 3:
				$cate = '+';
				break;
			case 4:
				$cate = '+';
				break;
		}
		return $cate;
	}

	/**
	 * 记录积分变动
	 * @param $user_id
	 * @param $type
	 * @param $note
	 * @param $value
	 * @param $growth_coin
	 * @return bool
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
    function ChangeValueLog($user_id,$type,$value,$note,$growth_coin)
    {
		$typelist = GrowthLog::$typelist;
		if (@!$typelist[$type]){
			return false;
		}

		$this->startTrans();

		$cate = $this->getTypeCase($type);

		$data = [
			'user_id' => $user_id,
			'cate' => $cate,
			'type' => $type,
			'change_value' => $value,
			'value_show' => $cate.$value,
			'value' => $growth_coin,
			'note' => $note,
			'add_time' => time(),
		];
//		print_r($data);die;

		$res = $this->save($data);
		if(!$res){
			return false;
		}
		$this->commit();
		return $this->{$this->pk};
	}

	// 获取用户积分记录
    function get_growth_record($condition,$field,$orderby = null,$limit){
        $where = null;
        if(!empty($condition['user_id'])){
            $where[] = ['user_id','=',$condition['user_id']];
        }
        $rs = $this
            ->where($where)
            ->field($field)
            ->where($where)
            ->order($orderby)
            ->paginate($limit);
        return $rs;
    }

//    插入兑换商品的积分记录
    function exchangerecord($orderid,$userinfo){
        $OrderModel = new Order();
        $join = [['ddt_shops s','o.shop_id = s.shop_id'],['ddt_orderdetail od','o.order_id = od.order_id']];
        $msginfo = $OrderModel->getJoinOrder([['o.order_id','=',$orderid]],'o.points,od.product_name,od.p_s_name,s.shop_name',$join);
        $note = $msginfo['shop_name'].'兑换'.$msginfo['product_name'].'('.$msginfo['p_s_name'].')';
        $rs = $this->ChangeValueLog($userinfo['user_id'],6,$msginfo['points'],$note,$userinfo['growth_coin']);
        if($rs === false){
            return false;
        }
        return true;
    }

	/**
	 * 计算让利折扣出来的利润分配
	 * @param $userInfo
	 * @param $paymentsid
	 * @param $type
	 * @return bool
	 * @throws \think\Exception
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 * @throws \think\exception\PDOException
	 */
	function CalculateProfit($userInfo,$paymentsid,$type){

	    $paymentModel = new Payments();
	    $paymentsInfo = $paymentModel->getOne(['payments_id'=>$paymentsid]);
		//计算让利分润额度
		//团长只有推荐积分 0.97%,普通用户 购买 0.22% 推荐 0.6%
		$amount = $paymentsInfo['amount'];//订单金额
        if($amount < 10){
            return true;
        }
        $settingModel = new Settings();
        $userModel = new User();
        $list = $settingModel->get_list(array("setg"=>"profit"))->toArray();
        $plist = array_column($list,'value','key');
        if($userInfo['is_sales'] != 2){
            $profit_me = calculate([$amount,$plist['buyprofit']],'*','2');
            $note = '用户单号'.trim($paymentsInfo['orderno'],',')."下单购物积分";
            $i_rs = $this->ChangeValueLog($userInfo['user_id'],$type,$profit_me,$note,$userInfo['growth_coin']);
            if($i_rs === false){
                $this->setError(-1,'插入积分记录失败');
                $this->rollback();
                return false;
            }
            $u_rs = $userModel->where("user_id",'=',$userInfo['user_id'])->setInc('growth_coin',$profit_me);
            if($u_rs === false){
                $this->setError(-1,'更新用户购买积分失败');
                return false;
            }
        }
        if($userInfo['invite_uid'] == 0){
            return true;
        }
        $invite_user = $userModel->getOne(['user_id'=>$userInfo['invite_uid']]);
        if(empty($invite_user)){
            return true;
        }
        $key = $invite_user['is_sales'] == 1?'recommendprofit':'agentprofit';
		$user_profit = calculate([$amount,$plist[$key]],'*','2');

        $integral_name = $type == 1?'购买商品获得':'预约服务获得';
		$note = '下级用户单号'.trim($paymentsInfo['orderno'],',')."下单{$integral_name}积分";
		$i_rs = $this->ChangeValueLog($invite_user['user_id'],4,$user_profit,$note,$invite_user['growth_coin']);
		if($i_rs === false){
			$this->setError(-1,'插入上级积分记录失败');
			$this->rollback();
			return false;
		}
        $u_rs = $userModel->where("user_id",'=',$invite_user['user_id'])->setInc('growth_coin',$user_profit);
        if($u_rs === false){
            $this->setError(-1,'更新上级用户购买积分失败');
            return false;
        }

//		return [
//			'amount' => $amount,//订单金额
//			'percentage' => $percentage,//店铺让利百分比
//			'profit' => $profit,//计算出来的总利润
//			'platform_profit' => $platform_profit,//平台获取的利润
//			'user_profit' => $user_profit,//用户获取的利润
//			'sales_profit' => $sales_profit,//推销员获取的利润
//		];
        return true;
	}
}